package controllers;

import helpers.HeaderHelper;
import helpers.LanguageHelper;
import helpers.ObjectifyServiceHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import services.UpdateDomain;
import services.UpdateGoogleAdsense;
import services.UpdateGoogleAnalytic;
import services.UpdateIp;

import models.Domain;
import models.GoogleAdsense;
import models.GoogleAnalytic;
import models.Inlink;
import models.IpTrack;
import models.Outlink;
import models.RecentSite;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import debug.DomainDebug;

public class SiteInfoServlet extends HttpServlet {
	public void doGet (HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		//Set Header website
		HeaderHelper headerHelper = new HeaderHelper(request);
		LanguageHelper translate = new LanguageHelper(request);
		String path = ((HttpServletRequest) request).getRequestURI();
		
		Cache cache=null;
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           e.printStackTrace();
        }
		
		Domain domain = new Domain();
		IpTrack ipTrack = new IpTrack();
		GoogleAdsense ads = new GoogleAdsense();
		GoogleAnalytic googleAnalytic = new GoogleAnalytic();
		Inlink inlink = new Inlink();
		Outlink outlink = new Outlink();
		
		String domainName = URLDecoder.decode(path.toLowerCase().replaceAll("/s/", ""),"UTF-8");
		String cachename = "s_" + domainName;
		if (cache.containsKey(cachename)) {
        	domain = (Domain) cache.get(cachename);
        	System.out.println("List Domain: cache print");
        } else {
		
			if(domainName!=null&&domainName.length()>0 && UrlHelper.checkDomain(domainName))
			{
				ObjectifyServiceHelper.register();
				Objectify ofy = ObjectifyService.begin();
				try {
					domain = ofy.get(new Key<Domain>(Domain.class, domainName));
					//domain = ofy.query(Domain.class).filter("name", domainName).get();
				} catch (Exception e) {
					response.sendRedirect("/u/" + domainName);
				}
				
				if (domain.getIpAddress() != null && !domain.getIpAddress().isEmpty()) {
					try {
						ipTrack = ofy.get(new Key<IpTrack>(IpTrack.class, domain.getIpAddress().replaceAll("(#[0-9]+)*", "")));
						//ipTrack = ofy.query(IpTrack.class).filter("ip", domain.getIpAddress().replaceAll("(#[0-9]+)*", "")).get();
					} catch (Exception e) {
						ipTrack = new IpTrack();
					}
				}
				if (domain.getGoogleAdsense() != null && !domain.getGoogleAdsense().isEmpty()) {
					try {
						ads = ofy.get(new Key<GoogleAdsense>(GoogleAdsense.class, domain.getGoogleAdsense()));
						//ads = ofy.query(GoogleAdsense.class).filter("adsAccount", domain.getGoogleAdsense()).get();
					} catch (Exception e) {
						ads = new GoogleAdsense();
					}
					
				}
				if (domain.getGoogleAnalytic() != null && !domain.getGoogleAnalytic().isEmpty()) {
					try {
						googleAnalytic = ofy.get(new Key<GoogleAnalytic>(GoogleAnalytic.class, domain.getGoogleAnalytic()));
						//googleAnalytic = ofy.query(GoogleAnalytic.class).filter("ananyticAccount", domain.getGoogleAnalytic()).get();
					} catch (Exception e) {
						googleAnalytic = new GoogleAnalytic();
					}
				}
				
				try {
					inlink = ofy.get(new Key<Inlink>(Inlink.class, domainName));
					//inlink = ofy.query(Inlink.class).filter("domainName", domainName).get();
				} catch (Exception e) {
					inlink = new Inlink();
				}
				
				try {
					outlink = ofy.get(new Key<Outlink>(Outlink.class, domainName));
					//outlink = ofy.query(Outlink.class).filter("domainName", domainName).get();
				} catch (Exception e) {
					outlink = new Outlink();
				}
				
				//Set recentSiteView and update cache
				if (domain.getIpAddress() != null && !domain.getIpAddress().isEmpty()) {
					RecentSite.setRecentView(domainName);
					cache.put(cachename, domain);
				}
			} else {
				domain = new Domain();
			}
        }
		//Check domain exists
		response.setHeader( "Cache-Control", "public, max-age=86400");
		response.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		
		//Set header info
		headerHelper.setTitle(domainName + ", " + translate.getString("info_header_site"));
		headerHelper.setDescription(domainName + ", " + translate.getString("info_desc_site") + domain.getDescription());
		headerHelper.setKeywords(domainName + ", " + domain.getKeywords());
		headerHelper.setOgtitle(domainName + ", " + translate.getString("info_header_site"));
		headerHelper.setOgescription(domainName + ", " + translate.getString("info_desc_site") + domain.getDescription());
		headerHelper.setOgimage("http://immediatenet.com/t/t_a?Size=1024x768&URL=" + domainName);
		
		request.setAttribute("headerHelper", headerHelper);
		request.setAttribute("domain", domain);
		request.setAttribute("ipTrack", ipTrack);
		request.setAttribute("ads", ads);
		request.setAttribute("googleAnalytic", googleAnalytic);
		request.setAttribute("inlink", inlink);
		request.setAttribute("outlink", outlink);
		
		try {
			request.getRequestDispatcher("/pages/info.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
